<template>
  <div class="consultation-page">
    <div class="page-header">
      <h2>咨询管理</h2>
      <el-tag :type="isOnline ? 'success' : 'info'" size="large">
        {{ isOnline ? '在线' : '离线' }}
      </el-tag>
    </div>

    <!-- 咨询列表 -->
    <div class="consultation-list">
      <el-tabs v-model="activeTab" class="consultation-tabs">
        <el-tab-pane label="待回复" name="pending">
          <el-table v-loading="loading" :data="pendingList" style="width: 100%">
            <el-table-column prop="title" label="咨询标题" min-width="150" show-overflow-tooltip />
            <el-table-column prop="content" label="咨询内容" min-width="200" show-overflow-tooltip />
            <el-table-column prop="consultationType" label="咨询类型" width="120">
              <template #default="{ row }">
                {{ consultationTypeMap[row.consultationType] }}
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="提交时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-button type="primary" link @click="handleViewChild(scope.row)">
                  查看儿童
                </el-button>
                <el-button type="primary" link @click="handleReply(scope.row)">
                  回复
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="已回复" name="replied">
          <el-table v-loading="loading" :data="repliedList" style="width: 100%">
            <el-table-column prop="title" label="咨询标题" min-width="150" show-overflow-tooltip />
            <el-table-column prop="content" label="咨询内容" min-width="200" show-overflow-tooltip />
            <el-table-column prop="consultationType" label="咨询类型" width="120">
              <template #default="{ row }">
                {{ consultationTypeMap[row.consultationType] }}
              </template>
            </el-table-column>
            <el-table-column prop="doctorReply" label="回复内容" min-width="200" show-overflow-tooltip />
            <el-table-column prop="replyTime" label="回复时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.replyTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-button type="primary" link @click="handleViewChild(scope.row)">
                  查看儿童
                </el-button>
                <el-button type="primary" link @click="handleClose(scope.row)">
                  关闭
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="已关闭" name="closed">
          <el-table v-loading="loading" :data="closedList" style="width: 100%">
            <el-table-column prop="title" label="咨询标题" min-width="150" show-overflow-tooltip />
            <el-table-column prop="content" label="咨询内容" min-width="200" show-overflow-tooltip />
            <el-table-column prop="consultationType" label="咨询类型" width="120">
              <template #default="{ row }">
                {{ consultationTypeMap[row.consultationType] }}
              </template>
            </el-table-column>
            <el-table-column prop="doctorReply" label="回复内容" min-width="200" show-overflow-tooltip />
            <el-table-column prop="replyTime" label="回复时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.replyTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-button type="primary" link @click="handleViewChild(scope.row)">
                  查看儿童
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 回复对话框 -->
    <el-dialog
      v-model="replyDialogVisible"
      title="回复咨询"
      width="50%"
      :close-on-click-modal="false"
    >
      <div class="consultation-detail">
        <div class="detail-item">
          <label>咨询标题：</label>
          <span>{{ currentConsultation?.title }}</span>
        </div>
        <div class="detail-item">
          <label>咨询类型：</label>
          <span>{{ consultationTypeMap[currentConsultation?.consultationType] }}</span>
        </div>
        <div class="detail-item">
          <label>咨询内容：</label>
          <p class="content">{{ currentConsultation?.content }}</p>
        </div>
        <div class="detail-item">
          <label>回复内容：</label>
          <el-input
            v-model="replyContent"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="replyDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitting" @click="submitReply">
            确认回复
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 儿童详情对话框 -->
    <el-dialog
      v-model="childDialogVisible"
      title="儿童档案"
      width="80%"
      :close-on-click-modal="false"
    >
      <div v-loading="childInfoLoading" class="child-profile">
        <!-- 基本信息卡片 -->
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span class="title">基本信息</span>
            </div>
          </template>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="姓名">{{ childInfo?.name || '--' }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ childInfo?.gender || '--' }}</el-descriptions-item>
            <el-descriptions-item label="年龄">{{ childInfo?.age ? `${childInfo.age}岁` : '--' }}</el-descriptions-item>
            <el-descriptions-item label="出生日期">{{ childInfo?.birthday ? formatDate(childInfo.birthday) : '--' }}</el-descriptions-item>
            <el-descriptions-item label="头像">
              <el-avatar :size="50" :src="childInfo?.avatar || defaultAvatar" />
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 生长发育记录卡片 -->
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span class="title">生长发育记录</span>
            </div>
          </template>
          <div v-if="childInfo?.growthRecords?.length" class="growth-charts">
            <el-table :data="childInfo.growthRecords" border style="width: 100%">
              <el-table-column prop="date" label="检查日期" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.date) }}
                </template>
              </el-table-column>
              <el-table-column prop="height" label="身高(cm)" width="120" />
              <el-table-column prop="weight" label="体重(kg)" width="120" />
              <el-table-column prop="bmi" label="BMI" width="120" />
            </el-table>
          </div>
          <el-empty v-else description="暂无生长发育记录" />
        </el-card>

        <!-- 疫苗接种记录卡片 -->
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span class="title">疫苗接种记录</span>
            </div>
          </template>
          <div v-if="childInfo?.vaccineRecords?.length" class="vaccine-records">
            <el-table :data="childInfo.vaccineRecords" border style="width: 100%">
              <el-table-column prop="vaccineName" label="疫苗名称" />
              <el-table-column prop="vaccineDate" label="接种日期" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.vaccineDate) }}
                </template>
              </el-table-column>
              <el-table-column prop="nextDate" label="下次接种日期" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.nextDate) }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.status === 1 ? 'success' : 'warning'">
                    {{ row.status === 1 ? '已完成' : '待接种' }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-empty v-else description="暂无疫苗接种记录" />
        </el-card>

        <!-- 体检记录卡片 -->
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span class="title">体检记录</span>
            </div>
          </template>
          <div v-if="childInfo?.checkupRecords?.length" class="checkup-records">
            <el-table :data="childInfo.checkupRecords" border style="width: 100%">
              <el-table-column prop="appointmentTime" label="体检日期" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.appointmentTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="checkupType" label="体检类型" width="120" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.status === 1 ? 'success' : 'warning'">
                    {{ row.status === 1 ? '已完成' : '待体检' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="result" label="体检结果" min-width="200" show-overflow-tooltip />
              <el-table-column prop="suggestion" label="医生建议" min-width="200" show-overflow-tooltip />
              <el-table-column label="操作" width="100" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" link @click="handleViewCheckup(row)">
                    查看详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-empty v-else description="暂无体检记录" />
        </el-card>
      </div>
    </el-dialog>

    <!-- 体检详情对话框 -->
    <el-dialog
      v-model="checkupDetailVisible"
      title="体检详情"
      width="60%"
      append-to-body
    >
      <div v-loading="checkupDetailLoading" class="checkup-detail">
        <template v-if="currentCheckup && checkupDetailData">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="体检日期">
              {{ formatDate(currentCheckup.appointmentTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="体检类型">
              {{ currentCheckup.checkupType }}
            </el-descriptions-item>
            <el-descriptions-item label="体检医院">
              {{ currentCheckup.hospital }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="currentCheckup.status === 1 ? 'success' : 'warning'">
                {{ currentCheckup.status === 1 ? '已完成' : '待体检' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>

          <div class="detail-section">
            <h3>检查项目详情</h3>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="检查项目">
                {{ checkupDetailData.itemName }}
              </el-descriptions-item>
              <el-descriptions-item label="检查结果">
                {{ checkupDetailData.itemValue }}{{ checkupDetailData.unit ? ` ${checkupDetailData.unit}` : '' }}
              </el-descriptions-item>
              <el-descriptions-item label="参考范围">
                {{ checkupDetailData.referenceRange || '--' }}
              </el-descriptions-item>
              <el-descriptions-item label="是否异常">
                <el-tag :type="checkupDetailData.isAbnormal === 1 ? 'danger' : 'success'">
                  {{ checkupDetailData.isAbnormal === 1 ? '异常' : '正常' }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>

            <div class="doctor-comment">
              <h4>医生建议</h4>
              <div class="detail-text">
                {{ checkupDetailData.doctorComment || '暂无建议' }}
              </div>
            </div>
          </div>
        </template>
        <el-empty v-else description="暂无体检详情数据" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getConsultationList, replyConsultation, closeConsultation } from '@/api/consultation'
import { getChildInfo, getCheckupDetail } from '@/api/child'
import dayjs from 'dayjs'

// 咨询类型映射
const consultationTypeMap = {
  'growth': '生长发育',
  'nutrition': '营养',
  'psychology': '心理',
  'other': '其他'
}

// 在线状态
const isOnline = ref(false)

// 标签页
const activeTab = ref('pending')
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 列表数据
const pendingList = ref([])
const repliedList = ref([])
const closedList = ref([])

// 回复对话框控制
const replyDialogVisible = ref(false)
const submitting = ref(false)
const currentConsultation = ref(null)
const replyContent = ref('')

// 儿童详情对话框控制
const childDialogVisible = ref(false)
const childInfoLoading = ref(false)
const childInfo = ref(null)

// 体检详情对话框控制
const checkupDetailVisible = ref(false)
const currentCheckup = ref(null)
const checkupDetailLoading = ref(false)
const checkupDetailData = ref(null)

// 添加默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 格式化日期
const formatDate = (date) => {
  if (!date) return '--'
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 获取列表数据
const fetchList = async () => {
  loading.value = true
  try {
    const res = await getConsultationList()
    console.log('咨询列表数据:', res)
    
    if (res && Array.isArray(res)) {
      // 如果直接返回数组（没有包装）
      handleConsultationData(res)
    } else if (res && res.code === 200 && Array.isArray(res.data)) {
      // 如果是包装的 Result 对象
      handleConsultationData(res.data)
    } else {
      console.error('返回数据格式错误:', res)
      ElMessage.error(res?.message || '获取咨询列表失败：数据格式错误')
    }
  } catch (error) {
    console.error('获取咨询列表失败:', error)
    ElMessage.error('获取咨询列表失败：' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 处理咨询数据
const handleConsultationData = (data) => {
  // 根据状态分类数据
  pendingList.value = data.filter(item => item.status === 0)
  repliedList.value = data.filter(item => item.status === 1)
  closedList.value = data.filter(item => item.status === 2)
  
  // 更新总数
  switch (activeTab.value) {
    case 'pending':
      total.value = pendingList.value.length
      break
    case 'replied':
      total.value = repliedList.value.length
      break
    case 'closed':
      total.value = closedList.value.length
      break
  }
}

// 查看儿童信息
const handleViewChild = async (row) => {
  childInfo.value = null
  childDialogVisible.value = true
  childInfoLoading.value = true
  
  try {
    const res = await getChildInfo(row.childId)
    console.log('获取到的儿童信息:', res)
    
    // 直接使用返回的数据对象
    if (res && res.id) {
      childInfo.value = res
    } else {
      console.error('响应数据格式不正确:', res)
      ElMessage.error('获取儿童信息失败：数据格式不正确')
    }
  } catch (error) {
    console.error('获取儿童信息失败:', error)
    ElMessage.error('获取儿童信息失败')
  } finally {
    childInfoLoading.value = false
  }
}

// 处理回复
const handleReply = (row) => {
  currentConsultation.value = row
  replyContent.value = ''
  replyDialogVisible.value = true
}

// 提交回复
const submitReply = async () => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }

  submitting.value = true
  try {
    const requestData = {
      id: currentConsultation.value.id,
      reply: replyContent.value
    }
    console.log('提交回复请求参数:', requestData)
    
    const res = await replyConsultation(requestData)
    console.log('提交回复响应数据:', res)
    
    // 因为是void返回，所以res为null是正常的
    ElMessage.success('回复成功')
    replyDialogVisible.value = false
    fetchList()
  } catch (error) {
    console.error('回复失败，错误信息:', error)
    ElMessage.error('回复失败：' + (error.message || '未知错误'))
  } finally {
    submitting.value = false
  }
}

// 关闭咨询
const handleClose = async (row) => {
  try {
    await ElMessageBox.confirm('确认关闭该咨询？', '提示', {
      type: 'warning'
    })
    
    const res = await closeConsultation(row.id)
    if (res && res.code === 200) {
      ElMessage.success('已关闭')
      fetchList()
    } else {
      ElMessage.error(res?.message || '关闭咨询失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('关闭咨询失败:', error)
      ElMessage.error('关闭咨询失败：' + (error.message || '未知错误'))
    }
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchList()
}

// 查看体检详情
const handleViewCheckup = async (record) => {
  currentCheckup.value = record
  checkupDetailVisible.value = true
  checkupDetailLoading.value = true
  checkupDetailData.value = null
  
  try {
    const res = await getCheckupDetail(record.id)
    console.log('获取到的体检详情数据:', res)
    
    if (res) {
      checkupDetailData.value = res
    } else {
      ElMessage.warning('暂无体检详情数据')
    }
  } catch (error) {
    console.error('获取体检详情出错:', error)
    ElMessage.error('获取体检详情失败')
  } finally {
    checkupDetailLoading.value = false
  }
}

onMounted(() => {
  fetchList()
})
</script>

<style scoped>
.consultation-page {
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.consultation-list {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.consultation-tabs {
  margin-bottom: 20px;
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  padding: 0 24px;
}

:deep(.el-tabs__item.is-active) {
  font-weight: 600;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.consultation-detail {
  padding: 20px 0;
}

.detail-item {
  margin-bottom: 20px;
}

.detail-item label {
  font-weight: 500;
  color: #606266;
  margin-bottom: 8px;
  display: block;
}

.detail-item .content {
  background: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
  margin: 8px 0;
  white-space: pre-wrap;
}

.child-profile {
  padding: 20px 0;
}

.profile-card {
  margin-bottom: 20px;
}

.profile-card:last-child {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header .title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.growth-charts,
.vaccine-records,
.checkup-records {
  margin-top: 16px;
}

:deep(.el-descriptions) {
  padding: 16px;
  background: #f5f7fa;
  border-radius: 4px;
}

:deep(.el-descriptions__label) {
  width: 100px;
  color: #606266;
}

:deep(.el-descriptions__content) {
  color: #303133;
}

:deep(.el-card__header) {
  padding: 12px 20px;
  border-bottom: 1px solid #ebeef5;
  background: #f5f7fa;
}

.detail-text {
  white-space: pre-wrap;
  line-height: 1.5;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;
  min-height: 60px;
}

.detail-section {
  margin-top: 24px;
}

.detail-section h3 {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
}

.doctor-comment {
  margin-top: 24px;
}

.doctor-comment h4 {
  font-size: 14px;
  font-weight: 600;
  color: #606266;
  margin-bottom: 12px;
}
</style> 